package gui.Persist;

import bin.Armazem;
import bin.err.Erro;
import gui.JanelaPrincipal;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.event.PrintJobEvent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author Eduardo Ott
 */
public class JanelaPersistencia extends javax.swing.JFrame {

    /**
     * Creates new form JanelaPersistencia
     */
    public JanelaPersistencia() {
        initComponents();

        try {
            this.txtDir.setText(this.getProperty());
        } catch (IOException ex) {
            new Erro(ex, "Erro ao abrir arquivo de configuração.", true);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtDir = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btConcluir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Persistência");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/Images/bd.png"))); // NOI18N

        jLabel2.setText("Diretório para persistência:");

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtDir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btCancelar.png"))); // NOI18N
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        btConcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btConcluir.png"))); // NOI18N
        btConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConcluirActionPerformed(evt);
            }
        });

        jLabel3.setText("Armazing Software     @Copyright");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
                        .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void importArmazem(File bd) throws IOException, ClassNotFoundException
    {
        Armazem armazem = null;
        if(!bd.exists())
        {
            bd.createNewFile();
            armazem = new Armazem();
            armazem.persistir(bd);
        }
        else
        {
            FileInputStream fis = new FileInputStream(bd);
            ObjectInputStream ois = new ObjectInputStream(fis);
            armazem = (Armazem)ois.readObject();
            ois.close();
            fis.close();
        }

        JanelaPrincipal janelaPrincipal = new JanelaPrincipal(bd, armazem);
        janelaPrincipal.setVisible(true);
    }
    
    public String getProperty() throws IOException {
        File f = new File("src\\gui\\Persist\\Connection.properties");
        if(f.exists())
        {
            f.createNewFile();
        }
        Properties prop = new Properties();
        
        FileReader fr = new FileReader(f);
        prop.load(fr);
        if(prop.getProperty("connect") == null)
        {
            FileWriter fw = new FileWriter(f);
            
            prop.setProperty("connect", System.getProperty("user.home"));
            prop.store(fw, "Salvo caminho de bd.dat");
        }
        
        return prop.getProperty("connect");
    }

    private void btConcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConcluirActionPerformed

        JanelaLoad janelaLoad = new JanelaLoad(this, false, "Carregando registros de:", "");
        try
        {
            File f = new File("src\\gui\\Persist\\Connection.properties");
            Properties prop = new Properties();
            FileWriter fw = new FileWriter(f);

            prop.setProperty("connect", this.txtDir.getText());
            prop.store(fw, "Salvo caminho de bd.dat");
            
            this.importArmazem(new File(prop.getProperty("connect") + "\\bd.dat"));
        }
        catch(IOException ex)
        {
            JOptionPane.showMessageDialog(this, "Erro ao definir arquivo bd.dat.\n" + ex, "Erro", JOptionPane.ERROR_MESSAGE);
            new Erro(ex, "Erro ao definir arquivo bd.dat", true);
        } 
        catch (ClassNotFoundException ex) 
        {
            JOptionPane.showMessageDialog(this, "Classe não encontrada\n." + ex, "Erro", JOptionPane.ERROR_MESSAGE);
            new Erro(ex, "Classe não encontrada", true);
        }
        finally
        {
            janelaLoad.dispose();
            this.dispose();
        }
    }//GEN-LAST:event_btConcluirActionPerformed

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
        
        this.dispose();

    }//GEN-LAST:event_btCancelarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int option = jfc.showOpenDialog(jfc);
        if (option == JFileChooser.APPROVE_OPTION) {
            this.txtDir.setText(jfc.getSelectedFile() + "");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btConcluir;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtDir;
    // End of variables declaration//GEN-END:variables
}
